package api

import (
	"github.com/gin-gonic/gin"
	"github.com/infraboard/mcube/v2/http/gin/response"
	"github.com/infraboard/mcube/v2/ioc"
	"gitlab.com/go-course-project/go17/vblog/apps/token"

	// 引入Gin Root Router: *gin.Engine
	"github.com/infraboard/mcube/v2/ioc/config/application"
	ioc_gin "github.com/infraboard/mcube/v2/ioc/config/gin"
	"github.com/infraboard/mcube/v2/ioc/config/log"
)

func init() {
	ioc.Api().Registry(&TokenApiHandler{})
}

type TokenApiHandler struct {
	ioc.ObjectImpl
	// 业务控制器
	token token.UserService
}

// router 也从ioc中 获取
func (h *TokenApiHandler) Init() error {
	h.token = token.GetService()

	// 在ioc获取gin server *gin.Engine
	ioc_gin.RootRouter()

	// 获取模块路有: url前缀,
	r := ioc_gin.ObjectRouter(h)
	r.POST("", h.IssueToken)
	r.DELETE("", h.RevolkToken)
	return nil
}

func (h *TokenApiHandler) Name() string {
	return "tokens"
}

func (h *TokenApiHandler) IssueToken(ctx *gin.Context) {
	in := token.NewIssueTokenRequest("", "")
	if err := ctx.BindJSON(in); err != nil {
		response.Failed(ctx, err)
		return
	}
	ins, err := h.token.IssueToken(ctx.Request.Context(), in)
	if err != nil {
		response.Failed(ctx, err)
		return
	}

	// 打印下日志, ioc
	domain := application.Get().Domain()
	log.L().Debug().Msgf("cookie domain: %s", domain)

	// 设置Cookie
	ctx.SetCookie(token.COOKIE_NAME, ins.AccessToken, ins.AccessTokenExpireTTL(), "/", domain, false, true)

	response.Success(ctx, ins)
}

func (h *TokenApiHandler) RevolkToken(ctx *gin.Context) {
	in := &token.RevolkTokenRequest{}
	if err := ctx.BindJSON(in); err != nil {
		response.Failed(ctx, err)
		return
	}
	ins, err := h.token.RevolkToken(ctx, in)
	if err != nil {
		response.Failed(ctx, err)
		return
	}
	response.Success(ctx, ins)
}
